<!DOCTYPE HTML>
<html>

<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <title>项目文件升级</title>
    <style>
        html,
        body {
            margin: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        .dragarea {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            border: 1px dashed rgb(27, 27, 189);
            text-align: left;
            border-radius: 8px;
            flex: 1;
            line-height: 1.5;
            padding: 10px;
            overflow: auto;
        }

        .dragarea notice {
            display: block;
            width: 100%;
            padding-top: 200px;
            text-align: center;
            color: #e1e1e1;
            cursor: pointer;
        }


        .dropcontext {
            position: relative;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: #e1e1e1;
            border-radius: 8px;
            padding: 10px;
            box-sizing: border-box;
            flex: 1;
        }

        .dropcontext ul {
            list-style-type: none;
        }

        .dropcontext li:after {
            clear: both;
        }

        .dropcontext ul:after {
            clear: both;
        }

        .dropcontext .need {
            color: rgb(25, 0, 253);
        }

        .dropcontext .update {
            color: #8f3a3a;
        }

        .dropcontext .defect {
            color: #ff0000;
        }

        .dropcontext:after {
            clear: both;
        }

        .pageheader {
            position: relative;
            height: 100px;
            text-align: left;
            color: #575656;
            background-color: #e1e1e1;
            border-radius: 4px;
            font-size: 12px;
        }

        .pageheader span {
            display: block;
            position: relative;
        }

        .page-container {
            position: relative;
            max-width: 1200px;
            margin: auto;

        }

        .uploadbtn {
            height: 50px;
            line-height: 50px;
            outline: none;
            width: 100%;
            box-sizing: border-box;
            border-radius: 4px;
            border: none;
            background-color: rgb(27, 114, 114);
            color: white;
            cursor: pointer;
        }

        .uploadbtn:hover {
            background-color: rgb(23, 173, 173);
        }

        .uploadbtn:disabled {
            background-color: #575656;
        }

        .pagebox {
            position: relative;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            padding: 20px 0px 20px 0;
    box-sizing: border-box;
        }

        .boxline {
            display: flex;
            flex-direction: row;
            flex: 1;
            height: 0;
        }

        ul {
            display: block;
            list-style-type: none;
            margin-block-start: 0em;
            margin-block-end: 0em;
            margin-inline-start: 0px;
            margin-inline-end: 0px;
            padding-inline-start: 0px;
            font-size: 12px;
            line-height: 1.5;
        }

        .pagecontext {
            position: absolute;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        .linesplit {
            height: 10px;
            width: 100%;
        }

        .lineverize {
            height: 100%;
            width: 10px;
        }
    </style>
        <link rel="stylesheet" type="text/css" href="../static/h-ui.admin/css/style.css" />
</head>

<body>
    <div class="pagecontext">

        <div class="page-container pagebox">

            <div class="serviceinfo"></div>

            <div class="linesplit"></div>
            <div class="boxline">
                <div class="dragarea js-drag item">
                    <notice>拖拽项目源码所有文件到此处</notice>
                    <ul></ul>
                </div>
                <div class="lineverize"></div>
                <div class="dropcontext">
                    <ul>
                    </ul>
                </div>
            </div>
            <div class="linesplit"></div>
            <div class="pageheader">
                <span></span>
            </div>
            <div class="linesplit"></div>
            <div class="divupload">
                <!-- <label>
                    <input type="file" style="display: none;" multiple value="添加" onchange="funcselectfile(this);">
                </label> -->
            </div>
            <div class="linesplit"></div>
            <div class="btnarea">
                <input type="button" value="同步" onclick="btnupload(this);" class="uploadbtn" disabled>
            </div>
            <div class="linesplit"></div>
        </div>
    </div>



    <script type="text/javascript" src="../lib/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="../lib/layer/2.4/layer.js"></script>
    <script type="text/javascript" src="../lib/api.js"></script>
    <script type="text/javascript" src="sparkmd5.js"></script>
    <script type="text/javascript">

        var pid = 0;
        var sid = 0;
        var modelid = 2;
        var mapconfig = new Map();
        var mapremote = new Map();

        $(window).ready(function () {
            // var pidstr = _apigetquery("id");
            // if (pidstr != null) {
            //     pid = parseInt(pidstr);
            // }

            var pidstr = _apigetquery("id");
            if (pidstr != null) {
                sid = parseInt(pidstr);
            }
            var modelstr = _apigetquery("mid");
            if (modelstr != null) {
                modelid = parseInt(modelstr);
            }

            _apiget("/api/spider/upload/info?serviceid=" + sid + "&model=" + modelid, true, function (code, obj) {
                if (code == 200) {
                        for (var k = 0; k < obj.configs.length; k++) {
                            var item = obj.configs[k];
                            if (!mapconfig.has(item.fileName)) {
                                mapconfig.set(item.fileName, item);
                            }
                        }
                    _appendmessage("读取文件配置完成!");
                    $(".serviceinfo").html("项目："+obj.service.name+" 镜像前缀："+obj.service.imagePrefix+" 上传路径："+obj.uploadpath);
                }
            });
            _apiget("/api/spider/upload/read?serviceid=" + sid + "&model=" + modelid, true, function (code, obj) {
                if (code == 200) {
                    if (obj.length > 0) {

                        var appendHtml = "";
                        for (var k = 0; k < obj.length; k++) {
                            var item = obj[k];
                            if (!mapremote.has(item.fullPath)) {
                                mapremote.set(item.fullPath, item);
                            }
                            appendHtml += "<li>" + item.fullPath + "</li>";
                        }
                        $(".dropcontext").find("ul").append(appendHtml);
                    }
                    _appendmessage("读取服务器文件完成！");
                }
            });
        });


        function readDirectory(directory) {
            return new Promise((resolve, reject) => {
                const dirReader = directory.createReader();
                let entries = [];
                const getEntries = function () {
                    dirReader.readEntries(
                        function (results) {
                            if (results.length) {
                                entries = entries.concat(results);
                                getEntries();
                            } else {
                                resolve(entries);
                            }
                        },
                        function (error) {
                            reject(error);
                        }
                    );
                };
                getEntries();
            });
        }

        async function readRoll(arr) {
            for (let key in arr) {
                if (arr[key].isDirectory) {
                    let result = await readDirectory(arr[key]);
                    arr[key] = result;
                    await readRoll(result);
                }
            }
        }

        function readFileEntry(fileEntry) {
            return new Promise((resolve, reject) => {
                fileEntry.file(
                    (fileData) => {
                        fileData.fullPath = fileEntry.fullPath;
                        resolve(fileData);
                    },
                    (error) => {
                        reject(error);
                    }
                );
            });
        }

        //export
        async function dropedFileReader(event) {
            if (!event.dataTransfer || !event.dataTransfer.items) {
                this.uploadLoading = false;
                throw new Error();
            }
            let fileEntryList = [];
            for (let item of event.dataTransfer.items) {
                fileEntryList.push(item.webkitGetAsEntry());
            }
            await readRoll(fileEntryList);
            fileEntryList = fileEntryList.flat(Infinity);
            const fileList = [];
            for (let item of fileEntryList) {
                let fileData = await readFileEntry(item);
                fileList.push(fileData);
            }
            return fileList;
        }


        //待上传的文件列表
        var _uploadlist = null;
        //加载的时候注册事件
        window.onload = function () {

            var dragElement = document.querySelector('.js-drag');
            //过滤文件格式
            var fileTypeArray = ['exe', 'pbo', 'less'];
            var file = {
                type: function (files, fileTypeArray) {
                    //这里做文件的过滤
                    if (_uploadlist == null) { _uploadlist = []; }
                    _uploadlist.push(files);
                },
                info: function (files) {
                    if (files.size > 0) {
                        file.type(files, fileTypeArray);
                    }
                }
            }

            var EventUtil = {
                addHandler: function (element, type, handler) {
                    if (element.addEventListener) {
                        element.addEventListener(type, handler, false);
                    } else if (element.attachEvent) {
                        element.attachEvent("on" + type, handler, false);
                    }
                },

                removeEventListener: function (element, type, handler) {
                    if (element.removeEventListener) {
                        element.removeEventListener(type, handler, false);
                    } else if (element.detachEvent) {
                        element.detachEvent("on" + type, handler, false);
                    }
                }
            }

            EventUtil.addHandler(dragElement, "drop", function (event) {
                event.preventDefault();
                event.stopPropagation();

                dropedFileReader(event).then((data) => {
                    for (let item of data) {
                        file.info(item);
                    }
                    _comparefile();
                });
            });

            EventUtil.addHandler(dragElement, "dragenter", function (event) {
                event.preventDefault();
                event.stopPropagation();
            });

            EventUtil.addHandler(dragElement, "dragover", function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        }

        var readmd5index = -1;
        function _readmd5() {
            readmd5index = readmd5index + 1;
            _readmd5item();
        }
        function _readmd5item() {

            if (readmd5index < _uploadlist.length) {
                var item = _uploadlist[readmd5index];
                if (item.filestate != -1) {
                    var spark = new SparkMD5();
                    spark.file(item, function (c, md) {
                        item.md5 = md;
                        _readmd5();
                    });
                } else {
                    _readmd5();
                }
            } else {
                readmd5index = -1;
                //对比差异
                for (var k = 0; k < _uploadlist.length; k++) {
                    var item = _uploadlist[k];
                    //上面监测多级文件夹
                    if (item.filestate == 0) {
                        //这里监测完整文件
                        if (mapconfig.has(item.fullPath)) {
                            var config = mapconfig.get(item.fullPath);
                            if (!config.ignore) {
                                item.filestate = 2;
                            }else{
                                item.filestate = -1;
                            }
                        } else {
                            if (mapremote.has(item.fullPath)) {
                                var one = mapremote.get(item.fullPath);
                                // if (one.utctime < item.utctime) {
                                //     item.filestate = 1;
                                // }
                                if (one.md5 != item.md5) {
                                    item.filestate = 1;
                                }
                            } else {
                                //远程没有，本地有
                                item.filestate = 3;
                            }
                        }
                    }
                }
                _showtoui();
            }
        }

        //对比文件
        function _comparefile() {



            // filestate=0:默认状态 -1:忽略  1:有变动  2:配置需要上传 3远程没有，需要上传 
            if (_uploadlist.length > 0) {
                var now = new Date();
                var timeoffset = now.getTimezoneOffset() * 60000;
                // var spark=new SparkMD5();
                for (var k = 0; k < _uploadlist.length; k++) {
                    var item = _uploadlist[k];
                    item.filestate = 0;

                    //这里需要回调... .. .
                    // spark.file(item,function(c,md){
                    //     item.md5=md;
                    // });
                    //转换成utctime
                    item.utctime = item.lastModified + timeoffset;
                    //根据文件名称，获取各个段的文件夹
                    //拆分文件夹
                    var dirs = _builddirectory(item.fullPath);
                    if (dirs) {
                        // console.log(dirs);
                        if (dirs.length > 0) {
                            for (var dir of dirs) {
                                if (mapconfig.has(dir)) {
                                    var config = mapconfig.get(dir);
                                    if (!config.ignore) {
                                        item.filestate = 2;
                                    } else {
                                        item.filestate = -1;//忽略
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                readmd5index = -1;
                _readmd5();

                //显示变动文件到UI
                // $(".uploadbtn").attr("disabeld", false);
            } else {
                _appendmessage("没有拖入文件");
            }
        }

        //生成多级目录
        function _builddirectory(full) {
            var newlist = new Array();
            var strs = full.split('/');
            strs.pop(); strs.shift();
            var temp = "/";
            for (var k = 0; k < strs.length; k++) {
                temp += strs[k] + "/";
                newlist.push(temp);
            }
            return newlist;
        }

        function _appendmessage(msg) {
            $(".pageheader").append("<span>" + (new Date()).Format("yyyy-MM-dd HH:mm:ss") + " " + msg + "</span>");
        }

        function _showtoui() {
            if (_uploadlist.length > 0) {
                $(".dragarea").find("notice").remove();
                var strHtml = "";
                for (var k = 0; k < _uploadlist.length; k++) {
                    var item = _uploadlist[k];
                    if (item.filestate > 0) {
                        strHtml += "<li>" + _buildspan(item.filestate) + " " + item.fullPath + "</li>";
                    }
                }
                $(".dragarea").find("ul").append(strHtml);
            }
            setTimeout(function () {
                $(".uploadbtn").attr("disabled", false);
            }, 100);
        }

        function _buildspan(state) {
            switch (state) {
                case 1: return '<span class="update">变动</span>';
                case 2: return '<span class="need">必须</span>';
                case 3: return '<span class="defect">缺失</span>';
            }
        }


        //选择文件
        function funcselectfile(e) {
            for (var k = 0; k < (e).files.length; k++) {
                var fileitem = (e).files[k];
                if (_uploadlist == null) { _uploadlist = []; }
                _uploadlist.push(fileitem);
            }
        }


        function btnupload(elc) {

            $(".uploadbtn").prop("disabled", true);
            uploadloadid = 0;
            // $(".uploadbtn").attr("disabeld", true);
            // setTimeout(function () {
            //     $(".uploadbtn").prop("disabled", true);
            // }, 100);
            _taketoupload();
        }


        var uploadloadid = 0;

        function _taketoupload() {

            if (uploadloadid == 0) {
                uploadloadid = layer.load();
            }

            if (_uploadlist.length > 0) {

                var item = _uploadlist.shift();
                if (item.filestate > 0) {
                    _uploaditem(item);
                } else {
                    _taketoupload();
                }

            } else {
                if (uploadloadid > 0) {
                    layer.close(uploadloadid);
                }
                _appendmessage("文件上传成功!");

                //更新版本
                // _apipost("/api/Home/SourceUpdate?projectid=" + pid, true, '', function (code, obj) {
                //     if (code == 200) {
                //         _appendmessage("项目版本升级成功");
                //     } else {
                //         _appendmessage("项目版本升级失败");
                //     }
                // });

            }

        }

        /**
         * 上传单个文件 
         */
        function _uploaditem(item) {
            if (item) {
                var fdata = new FormData();
                fdata.append("fullPath", item.fullPath);
                fdata.append("time", (new Date()).getTime());
                fdata.append("name", item.name);
                fdata.append(item.name, item);
                fdata.append("utctime", item.utctime);//转换成utctime
                fdata.append("lastModified", item.lastModified);//本地时间的time
                $.ajax({
                    url: "/api/spider/upload/drop?serviceid=" + sid + "&model=" + modelid,
                    type: 'post',
                    contentType: false,
                    processData: false,
                    async: true,
                    data: fdata,
                    headers: { "token": readToken() },
                    success: function (obj) {
                        // console.log(obj);
                    },
                    error: function (res) {
                        console.error(res);
                    },
                    complete: function () {
                        _taketoupload();
                    }
                });
            }
        };

    </script>
</body>

</html>